<!DOCTYPE HTML>
<html>
<body>

<canvas id="myCanvas">
    Your browser does not support the canvas element.
</canvas>

<canvas id="clipImgCanvas" width="300" height="300" style="background-color: #9E9E9E">

</canvas>

<script type="text/javascript">

    function drawMyCanvas() {

        var c = document.getElementById("myCanvas");
        var cxt = c.getContext("2d");
        var img = new Image()
        img.src = "http://www.w3cplus.com/sites/default/files/blogs/2018/1804/w3cplus-shang.png"
        img.onload = function () {
            console.log('加载图片完成才绘制，否则可能提前绘制导致图片不出');
            var imgSize = getNaturalSize(img);
            var w = imgSize.width;

            c.width = (w + 20) * 5;
            c.height = imgSize.height;

            for (var i = 0; i < 5; i++) {
                cxt.drawImage(img, w * i + 20, 0);
            }

            // cxt.drawImage(img, w * 2 + 10, 0);
            // cxt.drawImage(img, w * 3 + 10, 0);
            // cxt.drawImage(img, w * 4 + 10, 0);

        };


        function getNaturalSize(el) {
            var natureSize = {};
            if (window.naturalWidth && window.naturalHeight) {
                natureSize.width = el.naturalWidth;
                natureSize.height = el.naturalHeight;
            } else {
                var img = new Image();
                img.src = el.src;
                natureSize.width = img.width;
                natureSize.height = img.height;
            }
            return natureSize;
        }
    }

    function drawClipImgCanvas(){
        var canvas = document.getElementById("clipImgCanvas");
        var cxt = canvas.getContext("2d");
        var img = new Image()
        img.src = "";
        img.onload = function (e) {
            //原图，默认绘制
            cxt.drawImage(img, 0,0,img.width,img.height,0,0,img.width,img.height);
            //剪切。源图像，从（10，10）处开始绘制
            cxt.drawImage(img, 10,10,img.width,img.height,img.width,0,img.width,img.height);
            //缩放。
            cxt.drawImage(img, 0,0,img.width,img.height,0,img.height,30,30);
            //剪切并缩放
            cxt.drawImage(img, 10,10,img.width,img.height,img.width,img.height,img.width/2,img.height/2);

        }

    }


    drawMyCanvas();
    drawClipImgCanvas();
</script>


</body>
</html>
